package SecondeStage.Networkprogramming.Socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Tcp01Server {
    public static void main(String[] args) throws IOException {
        // 1. 在本机的9999端口监听，等待连接(要求9999端口没有其他服务在监听9999)
        ServerSocket serverSocket = new ServerSocket(9999);
        // 2. 当没有客户端连接9999端口时，程序会阻塞，等待连接
        // 如果有客户端连接，则会返回Socket对象，程序继续
        Socket socket = serverSocket.accept();
        System.out.println("socket = " + socket.getClass());
        // 3. 通过socket.getInputStream() 读取客户端写入到数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        // 4. IO读取
        byte[] buf = new byte[1024];
        int readlen =0;
        while ((readlen = inputStream.read(buf))!= -1){
            System.out.println(new String(buf,0,readlen));
        }
        // 5. 获取socket相关联的输出流
        OutputStream outputStream =socket.getOutputStream();
        outputStream.write("hello,client".getBytes());
        // 设置结束标记
        socket.shutdownOutput();
        // 6.关闭流和socket
        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }
}
